//
//  CMDBTopicDetailViewController.swift
//  CMDB
//
//  Created by 曹桂祥 on 17/4/14.
//  Copyright © 2017年 CMDB. All rights reserved.
//

import UIKit

class CMDBTopicDetailViewController: NormalTitleViewController {
    
    var detailTableView : CMDBHomeDetailTableView!
    
    var tid : String                = ""
    
    var toolView : UIView           = UIView.getInstance()
    
    var likeButton : UIButton       = UIButton.getInstance()
    
    var collectButton : UIButton    = UIButton.getInstance()
    
    var forwardButton : UIButton    = UIButton.getInstance()
    
    var commentButton : UIButton    = UIButton.getInstance()
    
    let btnWidth : CGFloat          = CMDB_Screen_Width / 4
    
    var detailData : CMDBDynamicBean?

    override func setup() {
        
        super.setup()
        
        buildTableView()
        
        buildToolView()
        
        loadRequest()
        
        setupNote()
    }
    
    func buildTableView(){
        
        let contentH     = CMDB_Screen_Height - KStatusBarHeight - KNavBarHeight - 45
        
        let contentFrame = CGRect(x: 0, y: 0, width: CMDB_Screen_Width, height: contentH)
        
        detailTableView                              = CMDBHomeDetailTableView(frame: contentFrame)
        detailTableView.separatorStyle               = .None
        detailTableView.showsVerticalScrollIndicator = false
//        detailTableView.mDelegate                    = self
        detailTableView.controller                   = self
        detailTableView.mDelegate                    = self
        contentView?.addSubview(detailTableView)
        
    }
    
    func buildToolView(){
        
        likeButton       = UIButton(title: "赞", imageName: "赞", selectedImage: "赞-选中", isSizeToFit: false,color: word54Color,titleSizeFont: CMDB_12_FONT)
        
        likeButton.frame = CGRect(x: 0, y: 0, width: btnWidth, height: 45)
        
        likeButton.addTarget(self, action: #selector(likeClicked), forControlEvents: .TouchUpInside)
        
        toolView.addSubview(likeButton)
        
        collectButton       = UIButton(title: "收藏", imageName: "收藏", selectedImage: "收藏-选中", isSizeToFit: false,color: word54Color,titleSizeFont: CMDB_12_FONT)
        collectButton.frame = CGRect(x: btnWidth, y: 0, width: btnWidth, height: 45)
        
        toolView.addSubview(collectButton)
        
        forwardButton       = UIButton(title: "转发", imageName: "转发", selectedImage: "转发-选中", isSizeToFit: false,color: word54Color,titleSizeFont: CMDB_12_FONT)
        forwardButton.frame = CGRect(x: btnWidth * 2, y: 0, width: btnWidth, height: 45)
        
        toolView.addSubview(forwardButton)
        
        commentButton       = UIButton(title: "评论", imageName: "评论", selectedImage: "评论-选中", isSizeToFit: false,color: word54Color,titleSizeFont: CMDB_12_FONT)
        commentButton.frame = CGRect(x: btnWidth * 3, y: 0, width: btnWidth, height: 45)
        
        commentButton.addTarget(self, action: #selector(publishComment), forControlEvents: .TouchUpInside)
        
        toolView.addSubview(commentButton)
        
        let topLine         = UIView(frame:CGRect(x: 0, y: 0, width: CMDB_Screen_Width, height: 0.5))
        
        topLine.backgroundColor = UIColor.Hex6(0x000000, alpha: 0.12)
        
        toolView.addSubview(topLine)
        
        let bottomLine      = UIView(frame:CGRect(x:0, y: 45.5, width: CMDB_Screen_Width, height: 0.5))
        
        bottomLine.backgroundColor = UIColor.Hex6(0x000000, alpha: 0.12)
        
        toolView.addSubview(bottomLine)
        
        
        view.addSubview(toolView)
        
        toolView.snp_makeConstraints { (make) in
            make.left.equalTo(0);
            make.right.equalTo(0);
            make.bottom.equalTo(0);
            make.height.equalTo(45)
        }
    }
}

extension CMDBTopicDetailViewController{
    
    func loadRequest(){
        
        do{
            let detailParam = CMDBDynamicDetailParam()
            
            detailParam.tid = tid
            
            try CMDBDynamicManager.getInstance.queryDynamicDetail(detailParam, handler: { [weak self](dynamic) in
                
                    self!.detailTableView.updateHeaderData(dynamic)
                
                    self!.detailData = dynamic
                
                    if (Int(dynamic.commentCount) > 0){
                        
                        self!.updateCommentCounts(dynamic.comments!.count)
                        
                        self!.detailTableView.updateDataWithOutReload(dynamic.comments)
                        
                        self!.detailTableView.updateCellAdpaters(dynamic.comments!, isInsert: false)
                    }
                    
                    if (Int(dynamic.likeCount) > 0){
                        
                        
                        if (Int(dynamic.isLike) == 1) {
                            self!.likeButton.selected = true
                            self!.likeButton.setTitle("\(dynamic.likeCount)", forState: .Selected)
                        }else{
                            self!.likeButton.selected = false
                            self!.likeButton.setTitle("\(dynamic.likeCount)", forState: .Normal)
                        }
                        
                    }else{
                        
                        self!.likeButton.selected = false
 
                    }

                }, error: { (rescode) in
                    
                }, failure: {
                    
            })
            
        }catch {
            
        }
    }
}


//MARK:- action methods
extension CMDBTopicDetailViewController{
    
    @objc func publishComment(){
        
        let publishVC = CMDBPublishCommentsViewController()
        
        publishVC.tid = tid
        
        publishVC.commentCount = Int((self.detailData?.commentCount)!)!
        
        publishVC.dataBlock = {(string,count,_) in
            
            let addedCount  = count as! Int
            
            let totalCount  = addedCount + Int(self.detailData!.commentCount)!
            
            self.commentButton.setTitle("\(totalCount)", forState: .Normal)
            
            self.dataBlock!("comment",1,nil)
            
            self.loadRequest()
            
        }
        
        navigationController?.pushViewController(publishVC, animated: true)
    }
}

//MARK:- action method
extension CMDBTopicDetailViewController{
    
    @objc func likeClicked(){
        
        likeButton.selected = !likeButton.selected
        
        if likeButton.selected {
            do{
                
                let likeParam = CMDBFansParam()
                
                likeParam.tid = self.tid

                try CMDBFansManager.getInstance.fans(likeParam, handler: { (isSuccess) in
                    
                    if isSuccess{
                        self.dataBlock!("like",1,nil)
                        
                        self.updateLikeButtonStatus()
                    }
                    
                    }, error: { (rescode) in
                        
                    }, failure: {
                        
                })
            }catch{
                
            }

        }else {
            
            do{
                
                let unlikeParam = CMDBCancleFansParam()
                
                unlikeParam.tid = self.tid
                
                try CMDBFansManager.getInstance.cancleFans(unlikeParam, handler: { (isSuccess) in
                    
                    if isSuccess{
                        self.dataBlock!("unLike",1,nil)
                        
                        self.updateLikeButtonStatus()
                    }
                    
                    }, error: { (rescode) in
                        
                    }, failure: {
                        
                })
            
            }catch{
                
            }
        
        
        }
    }
    
}

extension CMDBTopicDetailViewController{

    func updateLikeButtonStatus(){
        
        let likeCount = Int(likeButton.titleLabel!.text!) ?? 0
        
        if likeButton.selected {
            likeButton.setImage(UIImage(named: "赞-选中"), forState: .Selected)
            likeButton.setTitle("\(likeCount + 1)", forState: .Selected)
        }else{
            likeButton.setImage(UIImage(named: "赞"), forState: .Normal)
            if likeCount == 1{
                likeButton.setTitle("赞", forState: .Normal)
            }
        }
        
    }
}

extension CMDBTopicDetailViewController{
    
    override func onItemClickType(itemClickType: String?, data: AnyObject?, indexPath: NSIndexPath?) {
        printLog("ss")
    }
    
}

extension CMDBTopicDetailViewController{
    
    func updateCommentCounts(commentCount:Int){
        commentButton.setTitle("\(commentCount)", forState: .Normal)
    }
    
    
    func setupNote(){
        
        
        
    }
    
    override func popSelf() {
        
        
        NSNotificationCenter.defaultCenter().postNotificationName(AllowSliderDrawerNote, object: nil)
        
        super.popSelf()
        
    }
}
extension CMDBTopicDetailViewController{
    
    func onHeaderRefresh() {
        
        let commentListParama = CMDBCommentListParam()
        
        commentListParama.tid = self.tid
        
        commentListParama.ptime = "0"
        
        do {
            try CMDBCommentManager.getInstance.queryMoreComments(commentListParama, tableView: detailTableView, handler: { (commentList) in
                
                self.updateCommentCounts(commentList!.count)
                
                self.detailTableView.updateDataWithOutReload(commentList)
                
                self.detailTableView.updateCellAdpaters(commentList!, isInsert: false)
                
                
                }, error: { (rescode) in
                    
                }, failure: {
                    
            })
        }catch{
            
        }
    }

    
}

